//
//  WebchatDelegate.m
//  Showing
//
//  Created by Ralf on 5/4/15.
//  Copyright (c) 2015 com.next.starlooking. All rights reserved.
//

@import UIKit;

#import "WebchatDelegate.h"
#import "WXApi.h"
#import "iModern-Swift.h"

@implementation WebchatDelegate

- (void)login
{
    if ([WXApi isWXAppInstalled])
    {
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_message,snsapi_userinfo,snsapi_base,snsapi_friend,snsapi_contact";
        req.state = @"0744";
        [WXApi sendReq:req];
    }
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您没有安装微信，请换一种登录方式。" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
    }
}

- (void)share:(NSDictionary *)parameters
{
    _scene = WXSceneTimeline;
    WXMediaMessage *message   = [WXMediaMessage message];
    UIImage        *jpegImage = [UIImage imageWithData:[self imageWithImage:[parameters objectForKey:@"thumbImage"] scaledToSize:CGSizeMake(40, 80)]];
    [message setThumbImage:jpegImage];

    WXImageObject *ext = [WXImageObject object];
    ext.imageData         = [parameters objectForKey:@"imageData"];
    message.mediaObject   = ext;
    message.mediaTagName  = @"WECHAT_TAG_JUMP_APP";
    message.title         = [parameters objectForKey:@"message"];
    message.messageAction = @"<action>dotalist</action>";

    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText   = NO;
    req.message = message;
    req.scene   = _scene;

    [WXApi sendReq:req];
}

- (void)shareToSomeOne
{
    _scene = WXSceneSession;
    WXMediaMessage *message = [WXMediaMessage message];
    message.mediaTagName  = @"WECHAT_TAG_JUMP_APP";
    message.messageExt    = @"跟我一起iModern吧";
    message.messageAction = @"<action>dotalist</action>";

    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.text    = @"我在iModern爱魔登,你在哪里?";
    req.bText   = YES;
    req.message = message;
    req.scene   = _scene;

    [WXApi sendReq:req];
}

- (void)weixinPay:(NSString *)orderNumber tip:(double)tip
{

    //根据服务器端编码确定是否转码
    NSStringEncoding enc;
    enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);

    PayTransactionManager *payManager = [PayTransactionManager new];
    ResultSet             *rs         = [payManager queryTransactionRecord:orderNumber];
    if (rs.statusCode == 200)
    {

    }
    rs = [payManager createWechatPayTransactionRecord:orderNumber tip:tip];
    if ([[rs.data objectForKey:@"return_code"] isEqualToString:@"FAIL"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"获取订单信息失败,请您联系管理人员，为您带来的不便，敬请谅解." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
    }
    else
    {
        NSMutableDictionary *dict = [rs toMutableDictionary];

        if (dict != nil)
        {
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0)
            {
                [[UIApplication sharedApplication] delegate];
                self.numberOfOrder           = [dict objectForKey:@"numberOfOrder"];
                ResultSet *updateStateResult = [payManager updateOrderState:self.numberOfOrder];
                if (updateStateResult.statusCode != 200)
                {
                    //修改状态失败
                    return;
                }

                NSString *time_stamp;
                time_t   now;
                time(&now);
                time_stamp = [NSString stringWithFormat:@"%ld", now];

                NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
                [signParams setObject:[dict objectForKey:@"appid"] forKey:@"appid"];
                [signParams setObject:[dict objectForKey:@"nonce_str"] forKey:@"noncestr"];
                [signParams setObject:@"Sign=WXPay" forKey:@"package"];
                [signParams setObject:[dict objectForKey:@"mch_id"] forKey:@"partnerid"];
                [signParams setObject:time_stamp forKey:@"timestamp"];
                [signParams setObject:[dict objectForKey:@"prepay_id"] forKey:@"prepayid"];
                [signParams setObject:[self createMd5Sign:signParams] forKey:@"sign"];
                //调起微信支付
                PayReq *req = [[PayReq alloc] init];
                req.openID    = [signParams objectForKey:@"appid"];
                req.partnerId = [signParams objectForKey:@"partnerid"];
                req.prepayId  = [signParams objectForKey:@"prepayid"]; /* 预支付订单 */
                req.nonceStr  = [signParams objectForKey:@"noncestr"]; /* 随机串，防重发 */
                req.timeStamp = time_stamp.intValue;
                req.package   = [signParams objectForKey:@"package"];
                req.sign      = [signParams objectForKey:@"sign"];
                [WXApi sendReq:req];
            }
        }
    }
}

- (void)onResp:(BaseReq *)resp
{

}

- (NSString *)createMd5Sign:(NSMutableDictionary *)dict
{
    NSMutableString *contentString = [NSMutableString string];
    NSArray         *keys          = [dict allKeys];
    //按字母顺序排序
    NSArray         *sortedArray   = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
    {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString   *categoryId in sortedArray)
    {
        if (![[dict objectForKey:categoryId] isEqualToString:@""] && ![categoryId isEqualToString:@"sign"] && ![categoryId isEqualToString:@"key"])
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [dict objectForKey:categoryId]];
        }
    }
    [contentString appendFormat:@"key=%@", @"8IefylGlzd3o1x78pggHhlVUATaLgLoR"];
    //得到MD5 sign签名
    NSString *md5Sign = [self md5:contentString];

    return md5Sign;
}

- (NSData *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, 40, 80)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, 0.05);
}

- (NSString *)md5:(NSString *)str
{
    const char    *cStr = [str UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (unsigned int) strlen(cStr), digest);

    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];

    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
    {
        [output appendFormat:@"%02X", digest[i]];
    }

    return output;
}

//sha1 encode
- (NSString *)sha1:(NSString *)str
{
    const char *cstr = [str cStringUsingEncoding:NSUTF8StringEncoding];
    NSData     *data = [NSData dataWithBytes:cstr length:str.length];

    uint8_t digest[CC_SHA1_DIGEST_LENGTH];

    CC_SHA1(data.bytes, (unsigned int) data.length, digest);

    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];

    for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
    {
        [output appendFormat:@"%02x", digest[i]];
    }

    return output;
}


@end
